package org.jeecg.modules.zcgl.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.jeecg.common.exception.JeecgBootException;
import org.jeecg.common.system.base.entity.DelFlagBaseEntity;
import org.jeecg.common.util.DateUtils;
import org.jeecg.common.util.ReflectHelper;
import org.jeecg.modules.api.enums.TradeStatusEnum;
import org.jeecg.modules.zcgl.entity.Order;
import org.jeecg.modules.zcgl.entity.OrderDetails;
import org.jeecg.modules.zcgl.entity.ReceivablesInfo;
import org.jeecg.modules.zcgl.enums.AttentionPayStatusEnum;
import org.jeecg.modules.zcgl.mapper.OrderDetailsMapper;
import org.jeecg.modules.zcgl.mapper.OrderMapper;
import org.jeecg.modules.zcgl.mapper.ReceivablesInfoMapper;
import org.jeecg.modules.zcgl.service.IOrderService;
import org.jeecg.modules.zcgl.tencent.service.IWxSendMessageService;
import org.jeecg.modules.zcgl.tencent.vo.WxPayResultVo;
import org.jeecg.modules.zcgl.util.NoUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.Serializable;
import java.math.BigDecimal;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;

/**
 * @Description: 微信用户付款订单信息
 * @Author: jeecg-boot
 * @Date: 2020-07-13
 * @Version: V1.0
 */
@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements IOrderService {

    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private OrderDetailsMapper orderDetailsMapper;
    @Autowired
    private ReceivablesInfoMapper receivablesInfoMapper;
    @Autowired
    private IWxSendMessageService sendMessageService;

    @Override
    @Transactional
    public boolean saveMain(Order order, List<OrderDetails> orderDetailsList) {

        boolean bool = super.save(order);
        if (bool) {
            this.insertDetails(order, orderDetailsList);
        }
        return bool;
    }

    @Override
    @Transactional
    public boolean updateMain(Order order, List<OrderDetails> orderDetailsList) {
        boolean bool = super.updateById(order);

        //1.先删除子表数据
        orderDetailsMapper.deletePhysicalByMainId(order.getId());

        //2.子表数据重新插入
        if (bool) {
            this.insertDetails(order, orderDetailsList);
        }

        return bool;
    }

    @Transactional
    public void insertDetails(Order order, List<OrderDetails> orderDetailsList){
        if (orderDetailsList != null && orderDetailsList.size() > 0) {
            for (OrderDetails entity : orderDetailsList) {
                //外键设置
                entity.setOrderId(order.getId());
                entity.setCompanyId(order.getCompanyId());
                entity.setSysOrgCode(order.getSysOrgCode());
                orderDetailsMapper.insert(entity);
            }
        }
    }

    @Override
    @Transactional
    public boolean delPhysicalMain(String id) {
        boolean bool = orderDetailsMapper.deletePhysicalByMainId(id);
        if (bool) {
            orderMapper.deletePhysicalById(id);
        }
        return bool;
    }

    @Override
    @Transactional
    public boolean delMain(String id) {
        boolean bool = super.retBool(orderMapper.deleteById(id));
        if (bool) {
            orderDetailsMapper.deleteByMainId(id);
        }
        return bool;
    }

    @Override
    @Transactional
    public boolean delBatchMain(Collection<? extends Serializable> idList) {
        boolean bool = false;
        for (Serializable id : idList) {
            bool = this.delMain(id.toString());
            if (!bool) {
                throw new JeecgBootException("批量删除失败！");
            }
        }
        return bool;
    }

    @Override
    @Transactional
    public boolean updatePayStatusById(String id, Integer payStatus) {
        orderDetailsMapper.updatePayStatusByMainId(id, payStatus);
        orderMapper.updatePayStatusById(id, payStatus);
        return true;
    }

    @Override
    @Transactional
    public boolean updateWxPay(WxPayResultVo vo) {
//        Order order = orderMapper.selectByOrderNo(vo.getOut_trade_no());
//        if (order == null) {
//            log.error("微信支付返回订单查询失败，未找到订单。");
//            return;
//        }
//        int amountMoney = order.getAmountMoney().multiply(new BigDecimal(100)).intValue();
//        int payStatus = AttentionPayStatusEnum.SUCCESSFUL.getStatus();
//        //支付是否成功  支付金额是否和订单金额一致
//        if (!"SUCCESS".equalsIgnoreCase(vo.getReturn_code()) || !"SUCCESS".equalsIgnoreCase(vo.getResult_code()) || vo.getTotal_fee() != amountMoney) {
//            if (vo.getTotal_fee() != amountMoney) {
//                vo.setErr_code_des(vo.getErr_code_des() == null ? "" : vo.getErr_code_des() + "支付金额不一致");
//            }
//            payStatus = AttentionPayStatusEnum.FAILED.getStatus();
//        }
//        if (order.getPayStatus().intValue() == payStatus) {
//            return;
//        }
//        Date payDate = new Date();
//        try {
//            payDate = DateUtils.yyyymmddhhmmss.get().parse(vo.getTime_end());
//        } catch (Exception e) {
//        }
//        order.setPayDate(payDate);
//        order.setDeviceInfo(vo.getDevice_info());
//        order.setIsSubscribe(vo.getIs_subscribe());
//        order.setTradeType(vo.getTrade_type());
//        order.setBankType(vo.getBank_type());
//        order.setTransactionId(vo.getTransaction_id());
//        order.setErrCode(vo.getErr_code());
//        order.setErrCodeDes(vo.getErr_code_des());
//        order.setPayStatus(payStatus);
//
//        //查询订单详情，修改订单详情的状态
//        List<OrderDetails> orderDetailsList = orderDetailsMapper.selectByMainId(order.getId());
//        orderDetailsList.stream().forEach(orderDetails -> {
//            orderDetails.setPayStatus(order.getPayStatus());
//            orderDetails.setPayDate(order.getPayDate());
//            orderDetailsMapper.updateById(orderDetails);
//
//            //如果支付成功修改应收款项的支付状态
//            if (order.getPayStatus().intValue() == AttentionPayStatusEnum.SUCCESSFUL.getStatus()) {
//                ReceivablesInfo receivablesInfo = receivablesInfoMapper.selectById(orderDetails.getReceivablesId());
//                if (receivablesInfo != null) {
//                    receivablesInfo.setPayStatus(PayStatusEnum.PAID.getStatus());
//                    receivablesInfo.setPayType(PayTypeEnum.WECHAT_PAY.getStatus());
//                    receivablesInfo.setReceiptDate(order.getPayDate());
//                    receivablesInfo.setPaymentSlipNumber(order.getTransactionId());
//                    receivablesInfoMapper.updateById(receivablesInfo);
//                }
//            }
//        });
//
//        orderMapper.updateById(order);
//
//        sendMessageService.paymentSuccessful(vo.getOpenid(), order.getId());
        return true;
    }

//    @Override
//    @Transactional
//    public void creatorOrder(BigDecimal amountMoney, Integer orderType, ReceivablesInfo receivablesInfo) {
//        this.creatorOrder(amountMoney, orderType, receivablesInfo.getPayeeBy(), receivablesInfo);
//    }


    @Override
    @Transactional
    public boolean creatorOrder(BigDecimal amountMoney, Integer orderType, String customerId, ReceivablesInfo receivablesInfo) {

        //生成当前扣费的订单详情
        OrderDetails orderDetails = new OrderDetails();
        BeanUtils.copyProperties(receivablesInfo, orderDetails, ReflectHelper.getFiledName(DelFlagBaseEntity.class));
        orderDetails.setAmountMoney(amountMoney);
        orderDetails.setPayDate(DateUtils.getDate());
        orderDetails.setPaymentBy(customerId);
        orderDetails.setOrderType(orderType);
        orderDetails.setReceivablesId(receivablesInfo.getId());
        orderDetails.setCompanyId(receivablesInfo.getCompanyId());
        orderDetails.setSysOrgCode(receivablesInfo.getSysOrgCode());
        orderDetails.setPayStatus(AttentionPayStatusEnum.SUCCESSFUL.getStatus());

        Order order = new Order();
        order.setCustomerId(customerId);
        order.setTradeStatus(TradeStatusEnum.SUCCESS.getKey());
        order.setTradeTime(DateUtils.getDate());
//        order.setTransactionId();
//        order.setTradeType();
        order.setPayStatus(AttentionPayStatusEnum.SUCCESSFUL.getStatus());
        order.setAmountMoney(amountMoney);
        order.setOrderNo(NoUtils.getOrderNo());
        order.setOrderType(orderType);
        order.setRentCompanyId(receivablesInfo.getRentCompanyId());
        order.setCompanyId(receivablesInfo.getCompanyId());
        order.setSysOrgCode(receivablesInfo.getSysOrgCode());
        return this.saveMain(order, Arrays.asList(orderDetails));
    }

}
